package com.my.study.java.partiton;

import org.apache.kafka.clients.producer.Partitioner;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.utils.Utils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义分区
 *
 * 使用：props.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, DemoPartitioner.class.getName());
 *
 * @author: yidujun
 * @create: 2021/07/23 15:21
 */
public class DemoPartitioner implements Partitioner {

    private final AtomicInteger counter = new AtomicInteger(0);


    /**
     * 分区规则
     *
     * @param topic 主题
     * @param key key
     * @param keyBytes
     * @param value 消息
     * @param valueBytes
     * @param cluster kafka集群信息
     * @return
     */
    @Override
    public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) {
        // 获取kafka集群中主题为topic1的分区信息
        List<PartitionInfo> partitions = cluster.partitionsForTopic(topic);
        // 主题topic的分区数量
        int numPartitions = partitions.size();
        if (null == keyBytes) {
            return counter.getAndIncrement() % numPartitions;
        }
        else {
            // 指定了key，则对key使用哈希(采用MurmurHash2算法，具备高运算性能及低碰撞率),确定分区
            return Utils.toPositive(Utils.murmur2(keyBytes)) % numPartitions;
        }
    }

    @Override
    public void close() {

    }

    @Override
    public void configure(Map<String, ?> configs) {

    }
}
